package com.mylib.libcore.utils;

import com.mylib.libcore.BuildConfig;
import com.mylib.libcore.network.SSLSocketFactoryCompat;
import com.mylib.libcore.network.converter.gson.RQBGsonConverterFactory;
import com.mylib.libcore.network.converter.scalar.RQBScalarsConverterFactory;
import com.mylib.libcore.network.interceptor.CommonHeaderInterceptor;
import com.mylib.libcore.network.interceptor.CommonParamInterceptor;
import com.mylib.libcore.network.interceptor.LoggingInterceptor;
import com.mylib.libcore.network.interceptor.RetryIntercept;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.mylib.libcore.config.NetConfig;

import java.security.cert.CertificateException;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import me.jessyan.retrofiturlmanager.RetrofitUrlManager;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

import static com.mylib.libcore.config.NetConfig.BASE_MUSIC_API;
import static com.mylib.libcore.config.NetConfig.BASE_MUSIC_DJ_API;
import static com.mylib.libcore.config.NetConfig.BASE_MUSIC_PLAY_API;
import static com.mylib.libcore.config.NetConfig.BASE_WEATHER_API;

public class RetrofitUtil {

    private static Gson gson = new GsonBuilder()
            .setDateFormat("yyyy-MM-dd HH:mm:ss")
            .serializeNulls()
            .create();
    private static Retrofit appRetrofit = null;
    private static OkHttpClient appOkHttpClient = null;
    private static Retrofit appTouTiaoRetrofit = null;
    /**
     * 主接口
     * @return
     */
    public static Retrofit getAppRetrofit() {
        if (appRetrofit == null) {
            appRetrofit = createAppRetrofit();
        }
        return appRetrofit;
    }

    /**
     * 头条新闻接口
     * @return
     */
    public static Retrofit getTouTiaoRetrofit() {
        if (appTouTiaoRetrofit == null) {
            appTouTiaoRetrofit = createTouTiaoRetrofit();
        }
        appTouTiaoRetrofit = createTouTiaoRetrofit();
        return appTouTiaoRetrofit;
    }


    /**
     * getAppOkHttpClient
     * @return
     */
    public static OkHttpClient getAppOkHttpClient() {
        if (appOkHttpClient == null) {
            appOkHttpClient = createAppOkHttpClient();
        }
        return appOkHttpClient;
    }

    /**
     * 创建createAppOkHttpClient
     * @return
     */
    private static OkHttpClient createAppOkHttpClient() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(NetConfig.NET_TIME_OUT_CONNECT, TimeUnit.SECONDS);
        builder.readTimeout(NetConfig.NET_TIME_OUT_READ, TimeUnit.SECONDS);
        builder.writeTimeout(NetConfig.NET_TIME_OUT_WRITE, TimeUnit.SECONDS);

        builder.addInterceptor(new CommonHeaderInterceptor());
        builder.addInterceptor(new CommonParamInterceptor());//是否添加body公用参数
        builder.addInterceptor(new RetryIntercept(NetConfig.NET_MAX_RETRY_TIMES));

        if (BuildConfig.DEBUG) {
            builder.addInterceptor(new LoggingInterceptor());
        }

        builder.sslSocketFactory(getSSLSocketFactory());

        OkHttpClient okHttpClient = RetrofitUrlManager.getInstance().with(builder).build();
        return okHttpClient;
    }

    /**
     * 创建APP主Retrofit
     */
    private static Retrofit createAppRetrofit() {
        return new Retrofit.Builder()
                .client(getAppOkHttpClient())
                .baseUrl(NetConfig.NET_BASE)
               // .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(RQBScalarsConverterFactory.create(gson))
                .addConverterFactory(RQBGsonConverterFactory.create(gson))
                .build();
    }

    /**
     * 创建TouTiao主Retrofit
     */
    private static Retrofit createTouTiaoRetrofit() {
        return new Retrofit.Builder()
                .client(getAppOkHttpClient())
                .baseUrl(NetConfig.BASE_TOU_TIAO)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(RQBScalarsConverterFactory.create(gson))
                //  .addConverterFactory(RQBGsonConverterFactory.create(gson))
                .build();
    }

    /**
     * 创建天气主Retrofit
     */
    public static Retrofit createWeatherRetrofit() {
        return new Retrofit.Builder()
                .baseUrl(BASE_WEATHER_API) //基础url,其他部分在GetRequestInterface里
                .addConverterFactory(GsonConverterFactory.create()) //Gson数据转换器
                .build();
    }

    /**
     * 创建音乐主DJRetrofit
     */
    public static Retrofit createMusicDJRetrofit() {
        return new Retrofit.Builder()
                .baseUrl(BASE_MUSIC_DJ_API) //基础url,其他部分在GetRequestInterface里
                .addConverterFactory(GsonConverterFactory.create()) //Gson数据转换器
                .build();
    }

    /**
     * 创建音乐主Retrofit
     */
    public static Retrofit createMusicRetrofit() {
        return new Retrofit.Builder()
                .baseUrl(BASE_MUSIC_API) //基础url,其他部分在GetRequestInterface里
                .addConverterFactory(GsonConverterFactory.create()) //Gson数据转换器
                .build();
    }

    /**
     * 创建音乐主Retrofit
     */
    public static Retrofit createMusicOtherRetrofit() {
        return new Retrofit.Builder()
                .baseUrl(BASE_MUSIC_PLAY_API) //基础url,其他部分在GetRequestInterface里
                .addConverterFactory(GsonConverterFactory.create()) //Gson数据转换器
                .build();
    }

    private static SSLSocketFactory getSSLSocketFactory() {

        X509TrustManager x509TrustManager = new X509TrustManager() {
            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[]{};
            }
        };

        SSLSocketFactory sslSocketFactory = null;
        try {
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, new TrustManager[]{x509TrustManager}, new java.security.SecureRandom());
            sslSocketFactory = sslContext.getSocketFactory();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return sslSocketFactory;
    }
}
